const router = require('express').Router()
const fs = require('fs/promises')
const { uuid, wrap } = require('../tool')
const { join, extname } = require('path')
const formidable = require('formidable')
const { public } = require('../config')
const { User, Article, Article_classif, Follow_log } = require('../config/sql')

const upimage = function (req, options) {
   return new Promise((resolve, reject) => {
      const form = formidable(options)
      form.parse(req, (err, fields, files) => {
         if (err) {
            reject('500')
         }
         const file = Object.values(files)
         if (!file.length) reject('315')
         resolve(file)
      })
   })
}
// 上传若干图片
{
   /**上传目录 */
   const uploadDir = join(public, '/userupimage')
   const maxFileSize = false

   router.post('/upimage', wrap(async (req, res) => {
      const files = await upimage(req, {
         uploadDir,
         filename: (name, ext, part) => {
            return uuid() + extname(part.originalFilename)
         },
         allowEmptyFiles: false
      })
      res.send({
         code: 200,
         files: files.map(a => ({
            url: a.newFilename,
            oldname: a.originalFilename
         }))
      })
   }))
}
{/**上传目录 */
   const uploadDir = join(public, '/profile')
   const maxFileSize = 1024 * 1024 * 5

   router.post('/modify/profile', wrap(async (req, res, next) => {
      //获取原头像
      const [user] = await User.findAll({
         attributes: ['uid', 'profile'],
         where: {
            uid: req.user.account
         }
      })
      const oldname = user.profile
      let bls = 0
      const [file] = await upimage(req, {
         maxFileSize,
         filename: (name, ext, part) => {
            return uuid() + extname(part.originalFilename)
         },
         uploadDir,
         filter() {
            bls++
            return bls <= 1
         },
         allowEmptyFiles: false
      })
      const profile = file.newFilename
      await User.update({
         profile
      }, {
         where: {
            uid: req.user.account
         }
      })
      if (oldname) {
         await fs.rm(join(public, 'profile', oldname))
      }
      res.send({
         code: 200,
         msg: '头像上传成功',
         url: profile
      })
   }))
}
router.post('/modify/nickname', wrap(async (req, res) => {
   const { user, body: { nickname } } = req
   await User.update({
      nickname
   }, {
      where: {
         uid: user.account
      }
   })
   res.send({
      code: 200,
      msg: '修改成功'
   })
}))

router.get('/info', wrap(async (req, res) => {
   const { user: { account: bid } } = req
   const { length: fans } = await Follow_log.findAll({
      attributes: ['uid', 'bid'],
      where: {
         bid
      }
   })
   const articleSql = await Article.findAll({
      attributes: ['id', 'read'],
      where: {
         uid: bid
      }
   })
   const info = {
      read: 0,
      collection: 0,
      fans
   }
   const classif = await Article_classif.findAll({
      attributes: ['id', 'name'],
      where: {
         uid: bid
      }
   })
   const article = []
   for (const iterator of articleSql) {
      article.push(
         Object.assign({
            collection: await iterator.collection,
         }, iterator.dataValues)
      )
   }
   article.forEach(a => {
      info.read += a.read
      info.collection += a.collection
   })
   res.send({
      code: 200,
      info,
      classif
   })
}))

module.exports = router